package com.zcw.rabbitmq.chatroomv2;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DeliverCallback;

import java.io.IOException;


/**
 * 消息消费者
 */
public class Subscriber {

    public static final String CONSUMER_TAG = "chat_consumer";
    public static Channel channel;

    public static void getMessage(String roomName, String userName){
        String queueName = userName;
        // 获取房间
        if (channel == null) {
            channel = ChatRoom.getChatRoom(roomName, queueName);
        }
        try {
            // 接收消息成功的回调
            DeliverCallback deliverCallback = (consumerTag, delivery) ->{
                String message = new String(delivery.getBody(),"UTF-8");
                System.out.println("用户：" + queueName + "接收到消息：" + message);
            };

            // 从群聊中接收消息
            channel.basicConsume(queueName, true, deliverCallback, consumerTag -> {});
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}
